﻿using System.IO;
using System.Web;
using System.Web.Mvc;

namespace Kairos.Models
{
    public class ImageModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;

            var image = new Image();

            if (request.Files.Count == 0)
                return null;

            var file = request.Files[0];

            if (file == null)
                return null;

            if (file.ContentLength == 0)
                return null;

            image.FileName = Path.GetFileName(file.FileName);
            image.ContentType = file.ContentType;
            image.ContentLength = file.ContentLength;
            image.Data = new byte[image.ContentLength];

            file.InputStream.Read(image.Data, 0, image.ContentLength);

            return image;
        }
    }
}